package com.gxg.services;

import com.gxg.dao.PtitleDao;
import com.gxg.dao.VideoDao;
import com.gxg.entities.Ptitle;
import com.gxg.entities.Video;
import com.gxg.video.GetVideoFirst;
import com.gxg.video.VideoConvert;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.CriteriaBuilder;
import java.io.*;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.List;


/**
 * By 李朋飞
 **/
@Service
public class VideoService {
    @Autowired
    VideoDao videoDao;
    @Autowired
    GetVideoFirst getVideoFirst;
    @Autowired
    VideoConvert videoConvert;
    @Autowired
    PtitleDao ptitleDao;

    @Value("${course.video.dir}")
    private String videoResourcesUrl;
    @Value("${course.videoImg.dir}")
    private String videoImgResourcesUrl;
    @Value("${course.videoParentImg.dir}")
    private String videoParentImgResourcesUrl;
    @Value("${videoImg.webUrl}")
    private String videoImgWebUrl;
    @Value("${videoParentImg.webUrl}")
    private String videoParentImgWebUrl;
    @Value("${video.webUrl}")
    private String videoWebUrl;
    @Value("${page.size}")
    private Integer pageSize;

    public String videoUpload(String parentTitle, String childTitle, String teacherId, String videoClass, MultipartFile video, MultipartFile parentImg) throws IOException {
        JSONObject jsonObject = new JSONObject();
        if (video.isEmpty()) {
            jsonObject.accumulate("result", "error: 上传视频不可为空");
            return jsonObject.toString();
        }
        Timestamp time = new Timestamp(System.currentTimeMillis());
        String timeString = time.toString();
        timeString = timeString.split(" ")[0].split("-")[0] + timeString.split(" ")[0].split("-")[1] + timeString.split(" ")[0].split("-")[2] + timeString.split(" ")[1].split(":")[0] + timeString.split(" ")[1].split(":")[1] + timeString.split(" ")[1].split(":")[2].split("\\.")[0];
        String id = teacherId + timeString + (int) (100 + Math.random() * 999) + (int) (1000 + Math.random() * 9999);
        String videoOriginalName = video.getOriginalFilename();
        String videoType = videoOriginalName.substring(videoOriginalName.lastIndexOf(".") + 1);
        String videoName = childTitle + "-" + timeString + "." + videoType;
        String localUrl = videoResourcesUrl + videoName;
        String webUrl = videoWebUrl + videoName;
        String childImgName = childTitle + "-" + timeString + ".jpg";
        String childImgLocalUrl = videoImgResourcesUrl + childImgName;
        String childImgWebUrl = videoImgWebUrl + childImgName;
        List<Ptitle> ptitleList = ptitleDao.findByTeacherIdAndParentTitle(parentTitle, teacherId);
        if (ptitleList.size() == 0) {
            String parentImgOriginalName = parentImg.getOriginalFilename();
            String parentImgType = parentImgOriginalName.substring(parentImgOriginalName.lastIndexOf(".") + 1);
            String parentImgName = parentTitle + "-" + timeString + "." + parentImgType;
            String parentImgLocalUrl = videoParentImgResourcesUrl + parentImgName;
            String parentImgWebUrl = videoParentImgWebUrl + parentImgName;
            File localParentImg = new File(parentImgLocalUrl);
            try {
                parentImg.transferTo(localParentImg);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            Ptitle ptitle = new Ptitle(parentTitle, teacherId, parentImgWebUrl, parentImgLocalUrl, videoClass, time, time);
            Ptitle saveResult = ptitleDao.save(ptitle);
            if (saveResult == null) {
                jsonObject.accumulate("result", "error: 主标题创建失败");
                return jsonObject.toString();
            }
            File localVideo = new File(localUrl);
            try {
                video.transferTo(localVideo);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            try {
                getVideoFirst.fetchFrame(localVideo, childImgLocalUrl);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            Video saveVideo = new Video(id, parentTitle, childTitle, webUrl, localUrl, parentImgWebUrl, parentImgLocalUrl, childImgWebUrl, childImgLocalUrl, teacherId, videoClass, time, time);
            Video videoResult = videoDao.save(saveVideo);
            if (videoResult == null) {
                jsonObject.accumulate("result", "error: 数据库操作失败");
                return jsonObject.toString();
            }
            jsonObject.accumulate("result", "success");
            return jsonObject.toString();
        } else {
            try {
                File localVideo = new File(localUrl);
                video.transferTo(localVideo);
                getVideoFirst.fetchFrame(localVideo, childImgLocalUrl);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            Video saveVideo = new Video(id, ptitleList.get(0).getParentTitle(), childTitle, webUrl, localUrl, ptitleList.get(0).getParentImgWebUrl(), ptitleList.get(0).getParentImgLocalUrl(), childImgWebUrl, childImgLocalUrl, ptitleList.get(0).getTeacherId(), ptitleList.get(0).getVideoClass(), time, time);
            Video videoResult = videoDao.save(saveVideo);
            if (videoResult == null) {
                jsonObject.accumulate("result", "error: 数据库操作失败");
                return jsonObject.toString();
            }
            jsonObject.accumulate("result", "success");
            return jsonObject.toString();
        }

    }


    /**
     * 获取当前教师的视频
     * @param teacherId
     * @return
     */
    public String getMyVideoList(String teacherId){
        List<Video> videoList = videoDao.getVideoByTeacherId(teacherId);
        JSONObject videosJson = new JSONObject();
        videosJson.accumulate("videoList", videoList);
        return videosJson.toString();
    }

    /**
     * 通过本地视频路径删除视频
     * @param localUrl
     * @param imgLocalUrl
     * @return
     */
    public String deleteByLocalUrl(String localUrl, String imgLocalUrl){
        File video = new File(localUrl);
        File img = new File(imgLocalUrl);
        if (video.isFile()&&video.exists()){
            video.delete();
            if (img.isFile()&&img.exists()){
                img.delete();
                return videoDao.deleteByLocalUrl(localUrl);
            }else {
                return "服务器图片删除失败";
            }
        }else {
            return "服务器视频删除失败";
        }
    }

    /**
     * 获取所有视频
     * @return
     */
    public String getAllVideoList(){
        List<Video> videoList = videoDao.getVideo();
        JSONObject videosJson = new JSONObject();
        videosJson.accumulate("videoList", videoList);
        return videosJson.toString();
    }

    /**
     * 通过视频的地址返回老师的Id
     * @param webUrl
     * @return
     */
    public String getVideoByWebUrl(String webUrl){
        JSONObject jsonObject = new JSONObject();
        if (webUrl==null||webUrl.equals("")){
            jsonObject.accumulate("result","error: 路径为空");
            return jsonObject.toString();
        }
        List<Video> videoList = videoDao.findByChildImgWebUrl(webUrl);
        if (videoList.size()==0){
            jsonObject.accumulate("result","error: 没有视频");
            return jsonObject.toString();
        }
        jsonObject.accumulate("result","success");
        jsonObject.accumulate("videoList",videoList);
        return jsonObject.toString();
    }


    /**
     * 获取视频总页数
     * @return
     */
    public Integer getSumVideoPageCount(){
        Integer sumVideoCount = videoDao.getVideo().size();
        Integer sumVideoPageCount;
        Integer maxVideosEachPage = 6;
        if ((sumVideoCount % maxVideosEachPage) == 0){
            sumVideoPageCount = sumVideoCount / maxVideosEachPage;
        }else {
            sumVideoPageCount = sumVideoCount / maxVideosEachPage + 1;
        }
        return sumVideoPageCount;
    }

    /**
     * 获取当前页数的视频
     * @param pageNumber
     * @return
     */
    public String getPageVideoByPageNumber(Integer pageNumber){
        List<Video> videoList = videoDao.getVideo();
        Integer sumVideoCount = videoList.size();
        Integer maxVideosEachPage = 6;
        if(sumVideoCount >= maxVideosEachPage){
            if ((pageNumber * maxVideosEachPage) > sumVideoCount){
                List<Video> currVideoList = videoList.subList((pageNumber - 1)*maxVideosEachPage,sumVideoCount);
                JSONObject currPageVideoListJson = new JSONObject();
                currPageVideoListJson.accumulate("currPageVideoList", currVideoList);
                return currPageVideoListJson.toString();
            }else {
                List<Video> currVideoList = videoList.subList((pageNumber - 1)*maxVideosEachPage,(pageNumber)*maxVideosEachPage);
                JSONObject currPageVideoListJson = new JSONObject();
                currPageVideoListJson.accumulate("currPageVideoList", currVideoList);
                return currPageVideoListJson.toString();
            }
        }else {
            JSONObject currPageVideoListJson = new JSONObject();
            currPageVideoListJson.accumulate("currPageVideoList", videoList);
            return currPageVideoListJson.toString();
        }
    }

    /**
     * 获取老师当前页面的视频
     * @param teacherId
     * @param pageNumber
     * @return
     */
    public String getTeacherPageVideo(String teacherId, Integer pageNumber){
        List<Video> videoList = videoDao.getVideoByTeacherId(teacherId);
        Integer sumVideoCount = videoList.size();
        Integer maxVideosEachPage = 10;
        if(sumVideoCount >= maxVideosEachPage){
            if ((pageNumber * maxVideosEachPage) > sumVideoCount){
                List<Video> currVideoList = videoList.subList((pageNumber - 1)*maxVideosEachPage,sumVideoCount);
                JSONObject currPageVideoListJson = new JSONObject();
                currPageVideoListJson.accumulate("currPageVideoList", currVideoList);
                return currPageVideoListJson.toString();
            }else {
                List<Video> currVideoList = videoList.subList((pageNumber - 1)*maxVideosEachPage,(pageNumber)*maxVideosEachPage);
                JSONObject currPageVideoListJson = new JSONObject();
                currPageVideoListJson.accumulate("currPageVideoList", currVideoList);
                return currPageVideoListJson.toString();
            }
        }else {
            JSONObject currPageVideoListJson = new JSONObject();
            currPageVideoListJson.accumulate("currPageVideoList", videoList);
            return currPageVideoListJson.toString();
        }
    }

    /**
     * 获取老师视频的总数
     * @param teacherId
     * @return
     */
    public Integer getTeacherVideoSumNumber(String teacherId){
        Integer sumVideoCount = videoDao.getVideoNumberByTeacherId(teacherId);
        Integer sumVideoPageCount;
        Integer maxVideosEachPage = 10;
        if ((sumVideoCount % maxVideosEachPage) == 0){
            sumVideoPageCount = sumVideoCount / maxVideosEachPage;
        }else {
            sumVideoPageCount = sumVideoCount / maxVideosEachPage + 1;
        }
        return sumVideoPageCount;
    }

    /**
     * 通过类别获取该类别的视频总数
     * @param videoClass
     * @return
     */
    public Integer getVideoSumNumberByVideoClass(String videoClass){
        Integer sumVideoCount = videoDao.getVideoByVideoClass(videoClass).size();
        Integer sumVideoPageCount;
        Integer maxVideosEachPage = 6;
        if ((sumVideoCount % maxVideosEachPage) == 0){
            sumVideoPageCount = sumVideoCount / maxVideosEachPage;
        }else {
            sumVideoPageCount = sumVideoCount / maxVideosEachPage + 1;
        }
        return sumVideoPageCount;
    }

    /**
     * 获取当前页的某类视频
     * @param videoClass
     * @param pageNumber
     * @return
     */
    public String getClassVideo(String videoClass, Integer pageNumber){
        List<Video> videoList = videoDao.getVideoByVideoClass(videoClass);
        Integer sumVideoCount = videoList.size();
        Integer maxVideosEachPage = 6;
        if(sumVideoCount >= maxVideosEachPage){
            if ((pageNumber * maxVideosEachPage) > sumVideoCount){
                List<Video> currVideoList = videoList.subList((pageNumber - 1)*maxVideosEachPage,sumVideoCount);
                JSONObject currPageVideoListJson = new JSONObject();
                currPageVideoListJson.accumulate("currPageVideoList", currVideoList);
                return currPageVideoListJson.toString();
            }else {
                List<Video> currVideoList = videoList.subList((pageNumber - 1)*maxVideosEachPage,(pageNumber)*maxVideosEachPage);
                JSONObject currPageVideoListJson = new JSONObject();
                currPageVideoListJson.accumulate("currPageVideoList", currVideoList);
                return currPageVideoListJson.toString();
            }
        }else {
            JSONObject currPageVideoListJson = new JSONObject();
            currPageVideoListJson.accumulate("currPageVideoList", videoList);
            return currPageVideoListJson.toString();
        }
    }
    public String getParentVideo(String teacherId,Integer pageNumber,String videoClass,String parentTitle){
        JSONObject jsonObject = new JSONObject();
        if (pageNumber == null) {
            jsonObject.accumulate("result","error: 页码不能为空");
            return jsonObject.toString();
        }
        Sort sort = new Sort(Sort.Direction.DESC,"modificationTime");
        Pageable pageable = new PageRequest(pageNumber-1,pageSize,sort);
        if (teacherId == null){
            if (videoClass==null){
                List<Ptitle> ptitleList = ptitleDao.findAll(pageable);
                if (ptitleList.size()==0){
                    jsonObject.accumulate("result", "error: 没有视频合集");
                    return jsonObject.toString();
                }
                jsonObject.accumulate("result","success");
                jsonObject.accumulate("pageNumber",pageNumber);
                jsonObject.accumulate("parentList",ptitleList);
                return jsonObject.toString();
            }
            List<Ptitle> ptitleList = ptitleDao.findByVideoClass(videoClass,pageable);
            if (ptitleList.size()==0){
                jsonObject.accumulate("result", "error: 没有视频合集");
                return jsonObject.toString();
            }
            jsonObject.accumulate("result","success");
            jsonObject.accumulate("pageNumber",pageNumber);
            jsonObject.accumulate("parentList",ptitleList);
            return jsonObject.toString();
        }
        List<Ptitle> ptitleList = ptitleDao.findByTeacherId(teacherId,pageable);
        if (ptitleList.size()==0){
            jsonObject.accumulate("result", "error: 没有视频合集");
            return jsonObject.toString();
        }
        jsonObject.accumulate("result","success");
        jsonObject.accumulate("pageNumber",pageNumber);
        jsonObject.accumulate("parentList",ptitleList);
        return jsonObject.toString();
    }

    public String getVideoByTeacherIdAndParentTitle(String teacherId,String parentTitle,Integer pageNumber){
        JSONObject jsonObject = new JSONObject();
        if (teacherId==null||parentTitle==null){
            jsonObject.accumulate("result","error: 老师Id或者主标题为空");
            return jsonObject.toString();
        }
        Sort sort = new Sort(Sort.Direction.DESC,"modificationTime");
        Pageable pageable = new PageRequest(pageNumber-1,pageSize,sort);
        List<Video> videoList = videoDao.findByTeacherIdAndParentTitle(teacherId,parentTitle,pageable);
        if (videoList.size()==0){
            jsonObject.accumulate("result","error: 没有视频");
            return jsonObject.toString();
        }
        jsonObject.accumulate("result","success");
        jsonObject.accumulate("teacherId",teacherId);
        jsonObject.accumulate("parentTitle",parentTitle);
        jsonObject.accumulate("pageNumber",pageNumber);
        jsonObject.accumulate("videoList",videoList);
        return jsonObject.toString();
    }

    public String getSumNumber(String videoClass){
        JSONObject jsonObject = new JSONObject();
        if (videoClass==null){
            int sumNumber = ptitleDao.countAll();
            jsonObject.accumulate("result","success");
            jsonObject.accumulate("sumNumber",count(sumNumber));
            return jsonObject.toString();
        }
        int sumNumber = ptitleDao.countByVideoClass(videoClass);
        jsonObject.accumulate("result","success");
        jsonObject.accumulate("videoClass",videoClass);
        jsonObject.accumulate("sumNumber",count(sumNumber));
        return jsonObject.toString();
    }

    private int count(int sumVideoCount){
        int sumVideoPageCount;
        int maxVideosEachPage = pageSize;
        if ((sumVideoCount % maxVideosEachPage) == 0){
            sumVideoPageCount = sumVideoCount / maxVideosEachPage;
        }else {
            sumVideoPageCount = sumVideoCount / maxVideosEachPage + 1;
        }
        return sumVideoPageCount;
    }

    public String getChildVideoSumNumber(String teacherId, String parentTitle){
        JSONObject jsonObject = new JSONObject();
        if (teacherId==null||parentTitle==null){
            jsonObject.accumulate("result","error: 老师Id或者主标题");
            return jsonObject.toString();
        }
        jsonObject.accumulate("result","success");
        jsonObject.accumulate("sumNumber",count(videoDao.countByTeacherIdAndParentTitle(teacherId,parentTitle)));
        return jsonObject.toString();
    }
    public String getParentVideoSumNumberByTeacherId(String teacherId){
        JSONObject jsonObject = new JSONObject();
        if (teacherId==null){
            jsonObject.accumulate("result","error: teacherId为空");
            return jsonObject.toString();
        }
        jsonObject.accumulate("result","success");
        jsonObject.accumulate("sumNumber",ptitleDao.countByTeacherId(teacherId));
        return jsonObject.toString();
    }
    public String getParentVideoByTeacherId(String teacherId){
        JSONObject jsonObject = new JSONObject();
        if (teacherId==null){
            jsonObject.accumulate("result","error: teacherId为空");
            return jsonObject.toString();
        }
        List<Ptitle> ptitleList = ptitleDao.findByTeacherId(teacherId);
        if (ptitleList.size()==0){
            jsonObject.accumulate("result","error: 没有视频文件夹");
            return jsonObject.toString();
        }
        jsonObject.accumulate("result","success");
        jsonObject.accumulate("parentList",ptitleList);
        return jsonObject.toString();
    }
}
